<template>
  <div class="product-management">
    <!-- 查询表单 -->
    <el-form :inline="true" :model="queryForm" class="search-form">
      <el-form-item label="商品名称">
        <el-input v-model="queryForm.name" placeholder="请输入商品名称" clearable />
      </el-form-item>
      <el-form-item label="分类">
        <el-select v-model="queryForm.categoryId" placeholder="请选择分类" clearable>
          <el-option label="全部分类" value="" />
          <el-option 
            v-for="category in categories" 
            :key="category.id" 
            :label="category.name" 
            :value="category.id" 
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button type="success" @click="handleAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <!-- 商品表格 -->
    <div class="table-container">
      <el-table :data="productList" border style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="商品ID" width="80" />
        <el-table-column prop="name" label="商品名称" width="150" />
        <el-table-column prop="price" label="价格" width="100">
          <template #default="scope">
            ￥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="80" />
        <el-table-column prop="categoryLevel1Id" label="一级分类" width="100" />
        <el-table-column prop="categoryLevel2Id" label="二级分类" width="100" />
        <el-table-column prop="categoryLevel3Id" label="三级分类" width="100" />
        <el-table-column label="图片" width="100">
          <template #default="scope">
            <img 
              v-if="scope.row.fileName" 
              :src="require(`@/assets/files/${scope.row.fileName}`)" 
              class="product-thumb" 
              @error="handleImageError"
            />
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <div class="action-buttons">
              <el-button size="small" @click="handleView(scope.row)">查看</el-button>
              <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.current"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="50%" @close="resetForm">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入商品描述" 
          />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number 
            v-model="form.price" 
            :min="0" 
            :max="999999"
            :precision="2" 
            :step="0.01" 
            placeholder="请输入价格" 
          />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number 
            v-model="form.stock" 
            :min="0" 
            :max="999999"
            placeholder="请输入库存数量" 
          />
        </el-form-item>
        <el-form-item label="一级分类" prop="categoryLevel1Id">
          <el-select 
            v-model="form.categoryLevel1Id" 
            placeholder="请选择一级分类" 
            @change="handleCategoryLevel1Change"
          >
            <el-option 
              v-for="category in level1Categories" 
              :key="category.id" 
              :label="category.name" 
              :value="category.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类" prop="categoryLevel2Id">
          <el-select 
            v-model="form.categoryLevel2Id" 
            placeholder="请选择二级分类" 
            @change="handleCategoryLevel2Change"
          >
            <el-option 
              v-for="category in level2Categories" 
              :key="category.id" 
              :label="category.name" 
              :value="category.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="三级分类" prop="categoryLevel3Id">
          <el-select 
            v-model="form.categoryLevel3Id" 
            placeholder="请选择三级分类"
          >
            <el-option 
              v-for="category in level3Categories" 
              :key="category.id" 
              :label="category.name" 
              :value="category.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品图片" prop="fileName">
          <el-input v-model="form.fileName" placeholder="请输入图片文件名" />
          <div class="upload-tip">
            注意：请确保图片已上传到服务器，此处只需填写文件名（如：product1.jpg）
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 商品详情对话框 -->
    <el-dialog title="商品详情" v-model="detailVisible" width="40%">
      <div v-if="currentProduct">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="商品ID">{{ currentProduct.id }}</el-descriptions-item>
          <el-descriptions-item label="商品名称">{{ currentProduct.name }}</el-descriptions-item>
          <el-descriptions-item label="商品描述">{{ currentProduct.description || '暂无描述' }}</el-descriptions-item>
          <el-descriptions-item label="价格">￥{{ currentProduct.price }}</el-descriptions-item>
          <el-descriptions-item label="库存">{{ currentProduct.stock }}</el-descriptions-item>
          <el-descriptions-item label="一级分类ID">{{ currentProduct.categoryLevel1Id }}</el-descriptions-item>
          <el-descriptions-item label="二级分类ID">{{ currentProduct.categoryLevel2Id }}</el-descriptions-item>
          <el-descriptions-item label="三级分类ID">{{ currentProduct.categoryLevel3Id }}</el-descriptions-item>
          <el-descriptions-item label="图片">
            <img 
              v-if="currentProduct.fileName" 
              :src="require(`@/assets/files/${currentProduct.fileName}`)" 
              class="product-image-detail" 
              @error="handleImageError"
            />
            <span v-else>无图片</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div v-else>
        加载中...
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailVisible = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { queryProduct, getProduct, addProduct, updateProduct, deleteProduct } from '@/api/productApi'

export default {
  name: 'ProductManagementComponent',
  data() {
    return {
      // 查询表单
      queryForm: {
        name: '',
        categoryId: ''
      },
      // 商品列表数据
      productList: [],
      // 分类数据
      categories: [],
      level1Categories: [],
      level2Categories: [],
      level3Categories: [],
      // 分页数据
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      // 表单数据
      form: {
        id: '',
        name: '',
        description: '',
        price: 0,
        stock: 0,
        categoryLevel1Id: null,
        categoryLevel2Id: null,
        categoryLevel3Id: null,
        fileName: ''
      },
      // 文件列表
      fileList: [],
      // 对话框状态
      dialogVisible: false,
      dialogTitle: '',
      detailVisible: false,
      currentProduct: null,
      // 加载状态
      loading: false,
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入价格', trigger: 'blur' }
        ],
        stock: [
          { required: true, message: '请输入库存数量', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.fetchProductList()
    this.fetchCategories()
  },
  methods: {
    // 查询商品
    handleQuery() {
      this.pagination.current = 1
      this.fetchProductList()
    },
    // 获取商品列表
    async fetchProductList() {
      this.loading = true
      try {
        const params = {
          keyword: this.queryForm.name,  // 使用keyword参数而不是name
          pageNum: this.pagination.current,
          pageSize: this.pagination.size
        }
        const res = await queryProduct(params)
        if (res && res.data) {
          // 根据后端返回的数据结构进行处理
          if (Array.isArray(res.data)) {
            // 如果直接返回数组
            this.productList = res.data
            this.pagination.total = res.total || res.data.length
          } else if (res.data.data) {
            // 如果返回分页结构 { data: [...], total: 100 }
            this.productList = res.data.data
            this.pagination.total = res.data.total || res.total || 0
          } else {
            // 其他情况
            this.productList = []
            this.pagination.total = 0
          }
        } else {
          this.productList = []
          this.pagination.total = 0
        }
      } catch (error) {
        this.$message.error('获取商品列表失败: ' + (error.message || '未知错误'))
        console.error('获取商品列表错误:', error)
        this.productList = []
        this.pagination.total = 0
      } finally {
        this.loading = false
      }
    },
    // 获取分类数据
    async fetchCategories() {
      try {
        // 这里应该调用分类API获取分类数据
        // 暂时使用模拟数据，实际项目中应该调用真实的分类API
        this.categories = [
          { id: 541, name: '进口食品、生鲜', parentId: 0, type: 1 },
          { id: 548, name: '化妆品', parentId: 0, type: 1 },
          { id: 577, name: '手机、影像', parentId: 0, type: 1 },
          { id: 628, name: '家用商品', parentId: 0, type: 1 },
          { id: 660, name: '进口食品', parentId: 0, type: 1 },
          { id: 670, name: '电子商品', parentId: 0, type: 1 },
          { id: 676, name: '保健食品', parentId: 0, type: 1 },
          { id: 681, name: '箱包', parentId: 0, type: 1 },
          // 二级分类示例
          { id: 542, name: '生鲜', parentId: 541, type: 2 },
          { id: 543, name: '零食', parentId: 541, type: 2 },
          { id: 549, name: '面部护理', parentId: 548, type: 2 },
          { id: 550, name: '身体护理', parentId: 548, type: 2 },
          // 三级分类示例
          { id: 551, name: '面膜', parentId: 549, type: 3 },
          { id: 552, name: '洁面', parentId: 549, type: 3 },
          { id: 553, name: '爽肤水', parentId: 549, type: 3 }
        ]
        
        // 筛选各级分类
        this.level1Categories = this.categories.filter(category => category.parentId === 0)
        this.level2Categories = []
        this.level3Categories = []
      } catch (error) {
        console.error('获取分类数据失败:', error)
        this.$message.error('获取分类数据失败: ' + (error.message || '未知错误'))
      }
    },
    // 查看商品详情
    async handleView(row) {
      try {
        this.loading = true
        // 获取最新的商品详情
        const res = await getProduct(row.id)
        this.currentProduct = res
        this.detailVisible = true
      } catch (error) {
        this.$message.error('获取商品详情失败: ' + (error.message || '未知错误'))
        console.error('获取商品详情错误:', error)
      } finally {
        this.loading = false
      }
    },
    // 新增商品
    handleAdd() {
      this.dialogTitle = '新增商品'
      this.form = {
        id: '',
        name: '',
        description: '',
        price: 0,
        stock: 0,
        categoryLevel1Id: null,
        categoryLevel2Id: null,
        categoryLevel3Id: null,
        fileName: ''
      }
      this.fileList = []
      this.dialogVisible = true
    },
    // 编辑商品
    handleEdit(row) {
      this.dialogTitle = '编辑商品'
      // 确保价格和库存是有效值
      const price = isNaN(row.price) || row.price < 0 ? 0 : row.price
      const stock = isNaN(row.stock) || row.stock < 0 ? 0 : row.stock
      
      this.form = {
        id: row.id,
        name: row.name,
        description: row.description,
        price: price,
        stock: stock,
        categoryLevel1Id: row.categoryLevel1Id,
        categoryLevel2Id: row.categoryLevel2Id,
        categoryLevel3Id: row.categoryLevel3Id,
        fileName: row.fileName
      }
      this.fileList = row.fileName ? [{ name: row.fileName, url: `/api/images/${row.fileName}` }] : []
      this.dialogVisible = true
    },
    // 删除商品
    async handleDelete(row) {
      try {
        await this.$confirm(`确定删除商品《${row.name}》吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        this.loading = true
        await deleteProduct(row.id)
        this.$message.success('删除成功')
        this.fetchProductList()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      } finally {
        this.loading = false
      }
    },
    // 提交表单
    async submitForm() {
      try {
        if (!this.$refs.form) return
        const valid = await this.$refs.form.validate()
        if (!valid) return
        this.loading = true
        
        // 准备提交数据
        const data = {
          ...this.form
        }
        
        if (this.form.id) {
          // 更新商品
          await updateProduct(data)
          this.$message.success('更新成功')
        } else {
          // 新增商品
          await addProduct(data)
          this.$message.success('新增成功')
        }
        this.dialogVisible = false
        this.fetchProductList()
      } catch (error) {
        this.$message.error('操作失败: ' + (error.message || '请重试'))
        console.error('商品操作失败:', error)
      } finally {
        this.loading = false
      }
    },
    // 重置表单
    resetForm() {
      this.form = {
        id: '',
        name: '',
        description: '',
        price: 0,
        stock: 0,
        categoryLevel1Id: null,
        categoryLevel2Id: null,
        categoryLevel3Id: null,
        fileName: ''
      }
      this.fileList = []
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
    // 处理一级分类变化
    handleCategoryLevel1Change(value) {
      // 清空二级和三级分类
      this.form.categoryLevel2Id = null
      this.form.categoryLevel3Id = null
      // 筛选二级分类
      this.level2Categories = this.categories.filter(
        category => category.parentId === value && category.type === 2
      )
      this.level3Categories = []
    },
    // 处理二级分类变化
    handleCategoryLevel2Change(value) {
      // 清空三级分类
      this.form.categoryLevel3Id = null
      // 筛选三级分类
      this.level3Categories = this.categories.filter(
        category => category.parentId === value && category.type === 3
      )
    },
    // 处理文件上传成功
    handleUploadSuccess(response, file, fileList) {
      if (response && response.data) {
        this.form.fileName = response.data
      }
    },
    // 处理文件移除
    handleUploadRemove(file, fileList) {
      this.form.fileName = ''
    },
    // 处理分页大小改变
    handleSizeChange(size) {
      this.pagination.size = size
      this.fetchProductList()
    },
    // 处理分页页码改变
    handleCurrentChange(current) {
      this.pagination.current = current
      this.fetchProductList()
    },
    // 处理图片加载错误
    handleImageError(event) {
      event.target.src = require('@/assets/images/default_product.jpg')
    }
  }
}
</script>

<style scoped>
.product-management {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.table-container {
  margin-bottom: 20px;
}

.product-thumb {
  width: 50px;
  height: 50px;
  object-fit: cover;
}

.product-image-detail {
  max-width: 100%;
  max-height: 200px;
  object-fit: contain;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.action-buttons {
  display: flex;
  gap: 5px;
}

.upload-demo {
  width: 100%;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
</style>